package com.hkbigdata.sybx.service.ipml;

import com.hkbigdata.sybx.bean.OrderInfo;
import com.hkbigdata.sybx.mapper.OrderMapper;
import com.hkbigdata.sybx.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 订单服务实现类
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Override
    @Transactional
    public int createOrder(OrderInfo order) {
        // 设置订单默认状态为待确认
        order.setOrderStatus(1);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());

        return orderMapper.insert(order);
    }

    @Override
    public boolean updateOrderStatus(String orderNo, int orderStatus) {
        System.out.println("=== 开始更新订单状态 ===");
        System.out.println("订单号：" + orderNo);
        System.out.println("新状态：" + orderStatus);

        // 先查询当前订单状态
        OrderInfo currentOrder = orderMapper.selectByOrderNo(orderNo);
        if (currentOrder == null) {
            System.out.println("未找到订单：" + orderNo);
            return false;
        }
        System.out.println("当前订单状态：" + currentOrder.getOrderStatus());

        OrderInfo order = new OrderInfo();
        order.setOrderNo(orderNo);
        order.setOrderStatus(orderStatus);
        order.setUpdateTime(new Date());

        int result = orderMapper.updateStatusByOrderNo(order);
        System.out.println("更新结果：" + result);

        // 验证更新是否成功
        OrderInfo updatedOrder = orderMapper.selectByOrderNo(orderNo);
        System.out.println("更新后订单状态：" + (updatedOrder != null ? updatedOrder.getOrderStatus() : "null"));

        return result > 0;
    }

    @Override
    public OrderInfo getOrderByNo(String orderNo) {
        return orderMapper.selectByOrderNo(orderNo);
    }

    @Override
    public List<OrderInfo> getOrdersByUserId(String userId) {
        return orderMapper.selectByUserId(userId);
    }

    @Override
    public List<OrderInfo> getAllOrders() {
        return orderMapper.selectAllOrders();
    }

    @Override
    public boolean deleteOrder(String orderNo) {
        int result = orderMapper.deleteByOrderNo(orderNo);
        return result > 0;
    }

    @Override
    public boolean updateOrder(OrderInfo order) {
        // 设置更新时间
        order.setUpdateTime(new Date());
        int result = orderMapper.updateOrderInfo(order);
        return result > 0;
    }
} 